package com.pivotal.cloud.security.password;

import com.pivotal.cloud.crypto.codec.Hex;
import com.pivotal.cloud.crypto.codec.Utf8;
import com.pivotal.cloud.crypto.keygen.BytesKeyGenerator;
import com.pivotal.cloud.crypto.keygen.KeyGenerators;
import com.pivotal.cloud.crypto.utils.EncodingUtil;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @className: Pbkdf2PasswordEncoder
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Pbkdf2PasswordEncoder类，主要位于Security安全模块-Pbkdf2模式密码加密模块
 * @content: Pbkdf2PasswordEncoder-Pbkdf2模式密码加密
 * @author: Powered by Marklin
 * @datetime: 2025-06-24 13:32
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class Pbkdf2PasswordEncoder implements PasswordEncoder {

	private static final int DEFAULT_SALT_LENGTH = 16;

	private static final SecretKeyFactoryAlgorithm DEFAULT_ALGORITHM = SecretKeyFactoryAlgorithm.HmacSHA256;

	private static final int DEFAULT_HASH_WIDTH = 256; // SHA-256

	private static final int DEFAULT_ITERATIONS = 310000;

	private final BytesKeyGenerator saltGenerator;

	private final byte[] secret;

	private final int iterations;

	private String algorithm = DEFAULT_ALGORITHM.name();

	private int hashWidth = DEFAULT_HASH_WIDTH;

	private boolean overrideHashWidth = true;

	private boolean encodeHashAsBase64;

	/**
	 * 实例化对象
	 */
	private static final PasswordEncoder INSTANCE = Pbkdf2PasswordEncoder.newInstance();

	/**
	 * 获取实例
	 * @return 返回结果
	 */
	public static PasswordEncoder getInstance() {
		return INSTANCE;
	}

	/**
	 * 实例化对象
	 * @return 返回结果
	 */
	public static PasswordEncoder newInstance() {
		return defaultsPasswordEncoder();
	}

	/**
	 * Constructs a PBKDF2 password encoder with a secret value as well as salt length,
	 * iterations and algorithm.
	 * @param secret the secret
	 * @param saltLength the salt length (in bytes)
	 * @param iterations the number of iterations. Users should aim for taking about .5
	 * seconds on their own system.
	 * @param algorithm the algorithm to use
	 *
	 * @since 5.8
	 */
	public Pbkdf2PasswordEncoder(CharSequence secret, int saltLength, int iterations,
			SecretKeyFactoryAlgorithm algorithm) {
		this.secret = Utf8.encode(secret);
		this.saltGenerator = KeyGenerators.secureRandom(saltLength);
		this.iterations = iterations;
		setAlgorithm(algorithm);
	}

	/**
	 * Constructs a PBKDF2 password encoder with no additional secret value. There will be
	 * a salt length of 16 bytes, 310,000 iterations, SHA-256 algorithm and a hash length
	 * of 256 bits. The default is based upon aiming for .5 seconds to validate the
	 * password when this class was added. Users should tune password verification to
	 * their own systems.
	 * @return the {@link Pbkdf2PasswordEncoder}
	 *
	 * @since 5.8
	 */
	public static Pbkdf2PasswordEncoder defaultsPasswordEncoder() {
		return new Pbkdf2PasswordEncoder("", DEFAULT_SALT_LENGTH, DEFAULT_ITERATIONS, DEFAULT_ALGORITHM);
	}

	/**
	 * Sets the algorithm to use. See <a href=
	 * "https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SecretKeyFactory">SecretKeyFactory
	 * Algorithms</a>
	 * @param algorithm the algorithm to use (i.e.
	 * {@code SecretKeyFactoryAlgorithm.HmacSHA1},
	 * {@code SecretKeyFactoryAlgorithm.HmacSHA256},
	 * {@code SecretKeyFactoryAlgorithm.HmacSHA512})
	 *
	 * @since 5.0
	 */
	public void setAlgorithm(SecretKeyFactoryAlgorithm algorithm) {
		if (algorithm == null) {
			throw new IllegalArgumentException("secretKeyFactoryAlgorithm cannot be null");
		}
		String algorithmName = algorithm.name();
		try {
			SecretKeyFactory.getInstance(algorithmName);
			this.algorithm = algorithmName;
		}
		catch (NoSuchAlgorithmException ex) {
			throw new IllegalArgumentException("Invalid algorithm '" + algorithmName + "'.", ex);
		}
		if (this.overrideHashWidth) {
			this.hashWidth = SecretKeyFactoryAlgorithm.HmacSHA1.equals(algorithm) ? 160
					: SecretKeyFactoryAlgorithm.HmacSHA256.equals(algorithm) ? 256 : 512;
		}
	}

	/**
	 * Sets if the resulting hash should be encoded as Base64. The default is false which
	 * means it will be encoded in Hex.
	 * @param encodeHashAsBase64 true if encode as Base64, false if should use Hex
	 * (default)
	 */
	public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
		this.encodeHashAsBase64 = encodeHashAsBase64;
	}

	/**
	 * 密码加密
	 * @param rawPassword 原始密码
	 * @return 返回结果
	 */
	@Override
	public String encode(CharSequence rawPassword) {
		byte[] salt = this.saltGenerator.generateKey();
		byte[] encoded = encode(rawPassword, salt);
		return encode(encoded);
	}

	private String encode(byte[] bytes) {
		if (this.encodeHashAsBase64) {
			return Base64.getEncoder().encodeToString(bytes);
		}
		return String.valueOf(Hex.encode(bytes));
	}

	private byte[] decode(String encodedBytes) {
		if (this.encodeHashAsBase64) {
			return Base64.getDecoder().decode(encodedBytes);
		}
		return Hex.decode(encodedBytes);
	}

	private byte[] encode(CharSequence rawPassword, byte[] salt) {
		try {
			PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(),
					EncodingUtil.concatenate(salt, this.secret), this.iterations, this.hashWidth);
			SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm);
			return EncodingUtil.concatenate(salt, skf.generateSecret(spec).getEncoded());
		}
		catch (GeneralSecurityException ex) {
			throw new IllegalStateException("Could not create hash", ex);
		}
	}

	/**
	 * 验证密码
	 * @param rawPassword 原始密码
	 * @param encodedPassword 加密密码
	 * @return 返回结果
	 */
	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		byte[] digested = decode(encodedPassword);
		byte[] salt = EncodingUtil.subArray(digested, 0, this.saltGenerator.getKeyLength());
		return MessageDigest.isEqual(digested, encode(rawPassword, salt));
	}

	public enum SecretKeyFactoryAlgorithm {

		HmacSHA1, HmacSHA256, HmacSHA512

	}

}
